from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.models.user_model import User
from app import db
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
def register():
    try:
        logger.debug(f"Received register request headers: {dict(request.headers)}")
        logger.debug(f"Received register request data: {request.get_json()}")
        logger.debug(f"Request method: {request.method}")
        logger.debug(f"Request origin: {request.headers.get('Origin')}")
        
        data = request.get_json()
        if not data:
            logger.error("Invalid request data: no JSON data")
            return jsonify({'error': '无效的请求数据'}), 400
            
        required_fields = ['username', 'email', 'password']
        for field in required_fields:
            if field not in data:
                logger.error(f"Missing required field: {field}")
                return jsonify({'error': f'缺少必要字段: {field}'}), 400
        
        if User.query.filter_by(username=data['username']).first():
            logger.error(f"Username already exists: {data['username']}")
            return jsonify({'error': '用户名已存在'}), 400
            
        if User.query.filter_by(email=data['email']).first():
            logger.error(f"Email already exists: {data['email']}")
            return jsonify({'error': '邮箱已被注册'}), 400
        
        user = User(
            username=data['username'],
            email=data['email']
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()
        logger.info(f"User registered successfully: {data['username']}")
        
        response = jsonify({'message': '注册成功'}), 201
        logger.debug(f"Sending response: {response}")
        return response
    except Exception as e:
        logger.error(f"Error during registration: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    user = User.query.filter_by(username=data['username']).first()
    
    if user and user.check_password(data['password']):
        access_token = create_access_token(identity=str(user.id))
        return jsonify({
            'access_token': access_token,
            'user': user.to_dict()
        }), 200
    
    return jsonify({'error': '用户名或密码错误'}), 401

@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    current_user_id = get_jwt_identity()
    user = User.query.get(int(current_user_id))
    return jsonify(user.to_dict()), 200

# 检查是否为管理员的辅助函数
def _check_admin():
    current_user_id = get_jwt_identity()
    user = User.query.get(int(current_user_id))
    if not user or not user.is_admin():
        return False
    return True

# 用户管理接口 - 获取所有用户
@auth_bp.route('/users', methods=['GET'])
@jwt_required()
def get_all_users():
    # 检查权限
    if not _check_admin():
        return jsonify({'error': '权限不足，仅管理员可访问'}), 403
    
    try:
        users = User.query.all()
        return jsonify([user.to_dict() for user in users]), 200
    except Exception as e:
        logger.error(f"Error fetching users: {str(e)}")
        return jsonify({'error': str(e)}), 500

# 用户管理接口 - 添加用户
@auth_bp.route('/users', methods=['POST'])
@jwt_required()
def add_user():
    # 检查权限
    if not _check_admin():
        return jsonify({'error': '权限不足，仅管理员可访问'}), 403
    
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '无效的请求数据'}), 400
            
        required_fields = ['username', 'email', 'password']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'缺少必要字段: {field}'}), 400
        
        if User.query.filter_by(username=data['username']).first():
            return jsonify({'error': '用户名已存在'}), 400
            
        if User.query.filter_by(email=data['email']).first():
            return jsonify({'error': '邮箱已被注册'}), 400
        
        user = User(
            username=data['username'],
            email=data['email'],
            role=data.get('role', 'user')  # 默认为普通用户
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({'message': '用户添加成功', 'user': user.to_dict()}), 201
    except Exception as e:
        logger.error(f"Error adding user: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 用户管理接口 - 更新用户信息
@auth_bp.route('/users/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    # 检查权限
    if not _check_admin():
        return jsonify({'error': '权限不足，仅管理员可访问'}), 403
    
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        if not data:
            return jsonify({'error': '无效的请求数据'}), 400
        
        # 检查用户名唯一性
        if 'username' in data and data['username'] != user.username:
            if User.query.filter_by(username=data['username']).first():
                return jsonify({'error': '用户名已存在'}), 400
            user.username = data['username']
        
        # 检查邮箱唯一性
        if 'email' in data and data['email'] != user.email:
            if User.query.filter_by(email=data['email']).first():
                return jsonify({'error': '邮箱已被注册'}), 400
            user.email = data['email']
        
        # 更新密码
        if 'password' in data and data['password']:
            user.set_password(data['password'])
        
        # 更新角色
        if 'role' in data:
            user.role = data['role']
        
        db.session.commit()
        return jsonify({'message': '用户信息更新成功', 'user': user.to_dict()}), 200
    except Exception as e:
        logger.error(f"Error updating user: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 用户管理接口 - 删除用户
@auth_bp.route('/users/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    # 检查权限
    if not _check_admin():
        return jsonify({'error': '权限不足，仅管理员可访问'}), 403
    
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 检查是否为当前登录用户
        current_user_id = get_jwt_identity()
        if int(current_user_id) == user_id:
            return jsonify({'error': '不能删除当前登录的用户'}), 400
        
        db.session.delete(user)
        db.session.commit()
        return jsonify({'message': '用户删除成功'}), 200
    except Exception as e:
        logger.error(f"Error deleting user: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500 